<?php


namespace app\tickets\controller;


use app\api\controller\Commondevice;
use app\api\controller\Test;
use app\common\controller\Common;
use app\index\controller\Base;
use think\Config;
use think\Db;
use think\Exception;
use think\Session;

class Order extends Base
{

    /**
     * 删除会员
     * @author zhixuedong
     * @date 2021/2/2/002
     */
    public function cartDel(){
        try{
            $employeeNo = $_POST['id'];
            $detail = Db::name("tickets_list")->where(['id'=>$employeeNo])->find();
            $commondevice = new Test();
            $cartDel = $commondevice->cartDel($detail['signcode']);
            if($cartDel!==true){
                throw new Exception($cartDel['msg']);
            }
            Db::name("tickets_list")->where(['id'=>$employeeNo])->update(['status'=>2]);
            $black['code'] = 0;
            $black['msg'] = "操作成功";
        } catch (Exception $e) {
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return $black;
    }


    /**
     * 查询订单列表
     * @return mixed
     * @author zhixuedong
     * @date 2021/1/21/021
     */
    public function index()
    {
        $common = new Common();
        $thisWechat = Session::get("thisWechat");
        $where['uniacid'] = $thisWechat['id'];
        $where = "uniacid =" . $thisWechat['id'];
        if (!empty($_GET['keword'])) {
            $where .= " and (mobile like %" . $_GET['keword'] . "% or IDcard like %" . $_GET['keword'] . "% or name like %" . $_GET['keword'] . "%)";
        }
        if (!empty($_GET['status'])) {
            $where .= " and status = " . $_GET['status'];
        }
        //支付方式
        $paytype = "paytype";
        $paytypeWhere['status'] = 1;
        $payKey = $common->public_select($paytype, $paytypeWhere, "id,name")->select();
        $payValue = [];
        foreach ($payKey as $item) {
            $payValue[$item['id']] = $item['name'];
        }
        //订单状态
        $status_name = Config::get("Order_app_status");
        $this->assign("status_name", $status_name);
        if (!empty($_GET['type'])) {
            try {
                $page = empty($_GET['page']) ? 1 : $_GET['page'];
                $limit = empty($_GET['limit']) ? 10 : $_GET['limit'];
                $start = ($page - 1) * $limit;
                $is_pay = [1 => "未付款", 2 => "已支付"];
                $list = Db::name("tickets_order")->where($where)->limit($start, $limit)
                    ->order("id desc")->select();
                foreach ($list as $k => $v) {
                    $list[$k]['addtime'] = date("Y-m-d H:i:s", $v['addtime']);
                    $list[$k]['status_name'] = $status_name[$v['status']];
                    $list[$k]['is_pay'] = $is_pay[$v['is_pay']];
                    $list[$k]['pay_type'] = empty($v['pay_type']) ? "" : $payValue[$v['pay_type']];
                }
                $count = Db::name("tickets_order")->where($where)->limit($start, $limit)->count("*");
                $black['code'] = 0;
                $black['data'] = $list;
                $black['count'] = $count;
            } catch (Exception $e) {
                $black['code'] = 202;
                $black['msg'] = $e->getMessage();
            }
            return $black;
        }
        return $this->fetch('index');
    }


    /**
     * 查看订单详情
     * @author zhixuedong
     * @date 2021/1/21/021
     */
    public function detail()
    {
        $common = new Common();
        //订单状态
        $status_name = Config::get("Order_app_status");

        //支付方式
        $paytype = "paytype";
        $paytypeWhere['status'] = 1;
        $payKey = $common->public_select($paytype, $paytypeWhere, "id,name")->select();
        $payValue = [];
        foreach ($payKey as $item) {
            $payValue[$item['id']] = $item['name'];
        }

        //票类型
        $tickets_type = $common->publicAttribute("tickets_type");

        //支付状态
        $is_pay = [1 => "未付款", 2 => "已支付"];

        //查询订单详细信息
        $tickets_order = "tickets_order";
        $tickets_order_where['id'] = $_GET['id'];
        $order = $common->public_select($tickets_order, $tickets_order_where)->find();
        $order['status_name'] = $status_name[$order['status']];
        $order['pay_type'] = empty($order['pay_type'])?"":$payValue[$order['pay_type']];
        $order['is_pay'] = $is_pay[$order['is_pay']];

        //查询票种信息
        $tickets_order_detail = "tickets_order_detail";
        $order_detail_where['order_id'] = $_GET['id'];
        $detail = $common->public_select($tickets_order_detail, $order_detail_where)->find();

        $detail['type_name'] = empty($tickets_type[$detail['type']])?"未知":$tickets_type[$detail['type']];

        //查询日志信息
        $tickets_order_log = "tickets_order_log";
        $where['order_id'] = $_GET['id'];
        $log = $common->public_select($tickets_order_log, $where)->order("id desc")->select();

        //门票信息
        $tickets_list = "tickets_list";
        $list = $common->public_select($tickets_list, $where)->order("id desc")->select();
        $nowtime = date("Y-m-d");
        foreach ($list as $k=>$v){
            $status_name = "正常";
            if($v['status'] == 0){
                $status_name = "未生效";
            }
            if($v['status'] == 2){
                $status_name = "作废";
            }
            if($nowtime > $v['end_time']){
                $status_name = "作废";
            }
            $list[$k]['status_name'] = $status_name;
            $list[$k]['check_time'] = empty($v['check_time'])?"--":date("Y-m-d H:i:s",$v['check_time']);
        }

        $assign = ['order' => $order, 'detail' => $detail, 'log' => $log,'list'=>$list];
        $this->assign($assign);
        return $this->fetch('detail');
    }


    /**
     * 修改订单
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author zhixuedong
     * @date 2021/1/22/022
     */
    public function updateAddress()
    {
        $common = new Common();
        $type = $_POST['type'];
        if ($type == "updateAddress") {

            try {
                $data['id'] = $_POST['id'];
                $data['name'] = empty($_POST['name']) ? '' : $_POST['name'];
                $data['mobile'] = empty($_POST['mobile']) ? "" : $_POST['mobile'];
                $data['IDcard'] = empty($_POST['IDcard']) ? "" : $_POST['IDcard'];

                $table = "tickets_order";
                $common->handle($table, $data);

                $remark = empty($_POST['remark']) ? '' : $_POST['remark'];
                //生成订单操作流程
                $system_order_log = "tickets_order_log";
                $ordeLog['order_id'] = $_POST['id'];
                $ordeLog['title'] = "管理员修改了订单地址 操作人：" . Session::get("user_name");;
                $ordeLog['remark'] = $remark;
                $common->handle($system_order_log, $ordeLog);

                $black['status'] = 'success';
                $black['msg'] = "操作成功";
            } catch (Exception $e) {
                $black['code'] = 'error';
                $black['msg'] = $e->getMessage();
            }
            return $black;

        } else {
            //查询订单详细信息
            $tickets_order = "tickets_order";
            $tickets_order_where['id'] = $_REQUEST['id'];
            $field = "id,name,mobile,IDcard,remark";
            $detail = $common->public_select($tickets_order, $tickets_order_where, $field)->find();

            $this->assign([
                "detail" => $detail,
            ]);
            return view("updateAddress");
        }
    }


    /**
     *订单操作
     * @return mixed
     * @author zhixuedong
     * @date 2021/1/22/022
     */
    public function updateStatus()
    {
        $common = new Common();
        $id = $_POST['id'];
        $data['status'] = $status = $_POST['status'];
        $data['id'] = $id;
        $table = "tickets_order";
        $system_order_log = "tickets_order_log";
        $tickets_order_detail = "tickets_order_detail";
        $tickets_tickets = "tickets_tickets";
        Db::startTrans();
        try {
            switch ($status){
                //设为待核销
                case 2:
                    //生成订单操作流程
                    $ordeLog['order_id'] = $id;
                    $ordeLog['title'] = "管理员将订单设为待核销状态";
                    $ordeLog['remark'] = "管理员发送商品 操作人：".Session::get("user_name");
                    $common->handle($system_order_log, $ordeLog);
                    $common->handle($table, $data);  //更新订单状态
                    //更新生效时间
                    //Db::name("tickets_order_detail")->where(['order_id'=>$id])->update(['effective_time'=>date("Y-m-d")]);
                    break;
                case 6:
                    if(empty($_POST['cancel_reason']) || empty($_POST['cancel_remark'])){
                        throw new Exception("请完善取消原因等信息");
                    }
                    $data['cancel_reason'] = $_POST['cancel_reason'];
                    $data['cancel_remark'] = $_POST['cancel_remark'];

                    $tickets_order_where['id'] = $id;
                    $detail = $common->public_select($table, $tickets_order_where)->find();

                    $list = Db::name("tickets_list")->where(['order_id'=>$detail['id']])->select();
                    foreach ($list as $k=>$v){
                        $commondevice = new Test();
                        $commondevice->cartDel($v['signcode']);
                        Db::name("tickets_list")->where(['id'=>$v['id']])->update(['status'=>2]);
                    }

                    //已支付的订单
                    if($detail['is_pay']==2){
                        switch ($detail['pay_type']){
                            case "2":
                                //查询用户余额
                                $admin_fans = "admin_fans";
                                $fansWhere['id'] = $detail['fans_id'];
                                $balance = $common->public_select($admin_fans, $fansWhere)->value("balance");
                                $common->public_select($admin_fans, $fansWhere)->setInc('balance',$detail['real_pay']);
                                $log['fans_id'] = $detail['fans_id'];
                                $log['remark'] = Session::get("user_name")."取消订单退款入账";
                                $log['type'] = "balance";
                                $log['type_status'] = 1;
                                $log['number'] = $detail['real_pay'];
                                $log['before_number'] = $balance;
                                $log['after_number'] = $balance+$detail['real_pay'];
                                $log['operator_id'] = $detail['fans_id'];
                                $log['order_sn'] = $detail['order_sn'];
                                $common->createlog($log);
                                break;
                            case "1":
                                //微信支付原来退回
                                if($detail['refund']==1){
                                    //执行退款操作
                                    $tools = new Jsapi();
                                    $out_trade_no = $detail['order_sn'];
                                    $total_fee = $detail['real_pay']*100;
                                    $refund_fee = $detail['real_pay']*100;
                                    $jsApiParameters = $tools->refund($out_trade_no,$total_fee,$refund_fee);
                                    if($jsApiParameters['return_code']!='SUCCESS'){
                                        $this->msg($jsApiParameters['return_msg'], $jsApiParameters['return_msg'], "error");
                                    }
                                    if($jsApiParameters['result_code']!='SUCCESS'){
                                        $this->msg($jsApiParameters['err_code_des'], $jsApiParameters['err_code_des'], "error");
                                    }
                                    $data['refund'] = 2;
                                    $data['refund_fee'] = $detail['real_pay'];
                                }
                                break;
                        }


                    }

                    //生成订单操作流程
                    $ordeLog['order_id'] = $detail['id'];
                    $ordeLog['title'] = "管理员取消订单 操作人：".Session::get("user_name");
                    $ordeLog['remark'] = $data['cancel_remark'];
                    $common->handle($system_order_log, $ordeLog);

                    //或取商品列表
                    $order_detail_where['order_id'] = $id;
                    $field = "tickets_id,count";
                    $product = $common->public_select($tickets_order_detail, $order_detail_where,$field)->select();
                    foreach ($product as $k=>$v){
                        $tickets_ticketsWhere['id'] = $v['tickets_id'];
                        //库存增加
                        $common->public_select($tickets_tickets, $tickets_ticketsWhere)->setInc("inventory",$v['count']);
                        //已售减少
                        //$common->public_select($tickets_tickets, $tickets_ticketsWhere)->setDec("soldout",$v['count']);
                    }

                    $common->handle($table, $data);  //更新订单状态
                    break;
                case 3:
                    //设为已核销
                    //生成订单操作流程
                    $ordeLog['order_id'] = $id;
                    $ordeLog['title'] = "管理员将订单设为已核销状态";
                    $ordeLog['remark'] = "管理员将订单设为已核销状态 操作人：".Session::get("user_name");
                    $common->handle($system_order_log, $ordeLog);
                    $common->handle($table, $data);  //更新订单状态
                    break;
                case 'del':
                    //删除订单
                    $order_detailWhere['order_id'] = $id;
                    $tableWhere['id'] = $id;
                    $common->public_select($table, $tableWhere)->delete();
                    $common->public_select($tickets_order_detail, $order_detailWhere)->delete();
                    //记录操作日志
                    $log['remark'] = "用户【" . Session::get("user_name") . "】删除订单,关联id【".$id."】";
                    $common->addLog($log);
                    break;

            }

            Db::commit();
            $black['status'] = "success";
            $black['msg'] = "操作成功";
        } catch (Exception $e) {
            Db::rollback();
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return $black;
    }


    /**
     * 删除订单
     * @return mixed
     * @author zhixuedong
     * @date 2021/1/22/022
     */
    public function delOrder(){
        try{
            $common = new Common();
            $table = "tickets_order";
            $tickets_order_detail = "tickets_order_detail";
            $id = $_POST['id'];
            $where['id'] = ['in',$id];
            $where1['order_id'] = ['in',$id];
            $common->public_select($table, $where)->delete();
            $common->public_select($tickets_order_detail, $where1)->delete();
            //记录操作日志
            $id = implode(",",$id);
            $log['remark'] = "用户【" . Session::get("user_name") . "】删除订单,关联id【".$id."】";
            $common->addLog($log);
            $black['code'] = 0;
            $black['msg'] = "删除成功";
        }catch (Exception $e){
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return $black;
    }



}